app.config(function($routeProvider,$locationProvider){
    $routeProvider
        .when('/callCenter/index', {
            templateUrl:'callCenter/index.html',
            controller: 'callAnswerController'
        })
        .when('/callCenter/history', {
            templateUrl: "callCenter/history.html",
            controller: 'callHistoryController'
        })
        .when('/callCenter/message', {
            templateUrl: "callCenter/message.html",
            controller: 'callMessageController'
        })
        .when('/callCenter/edit/:code', {
            templateUrl: "callCenter/edit.html",
            controller: 'callEditController'
        }).when('/callCenter/historyExport', {
            templateUrl: "callCenter/historyExport.html",
            controller: 'callHistoryController'
        })
        .when('/callCenter/elderQuery', {
            templateUrl: "callCenter/elder-query.html",
            controller: 'elderQueryController'
        })
        .when('/callCenter/elderQueryResult/:code', {
            templateUrl: "callCenter/elder-query-result.html",
            controller: 'elderQueryResultController'
        });
});

function callCenterService( $http, $location ){

    return {

        answer : function( data, app_id, recall ){
            var params = {
                name     : data.name,
                phone     : data.phone
            };
            baas_yl.call({
                'http':$http,
                'method': 'post',
                'uri': 'callCenter/index/answer',
                'data':params,
                'success': function(d) {
                    if(d.status == '1'){
                        if( typeof recall == 'function'){
                            recall( d );
                        }
                    }else{
                        if( d.description ){
                            alert(d.description );
                        }else{
                            alert( '网络原因，请求失败，请稍后重试' );
                        }
                    }
                }
            });
        },
        update  : function( data,infos,calls, app_id, recall ){
            var data = {
                name: (typeof infos!="undefined"   && typeof infos.name != "undefined" && infos.name != '' )?infos.name:undefined, 
                address : (typeof infos!="undefined"   && typeof infos.address != "undefined" && infos.address != ''  )?infos.address:undefined,
                xingzheng_title : (typeof infos!="undefined"   && typeof infos.xingzheng_title != "undefined" && infos.xingzheng_title != ''  )?infos.xingzheng_title:undefined,
                jiedao_title : (typeof infos!="undefined"   && typeof infos.jiedao_title != "undefined"&& infos.jiedao_title != ''  )?infos.jiedao_title:undefined,
                shequ_title :(typeof infos!="undefined"   && typeof infos.shequ_title != "undefined" && infos.shequ_title != '' )?infos.shequ_title:undefined,
                service     : data.service,
                remark   : data.remark,
                phone   : data.phone==infos.contact_phone?data.phone:infos.contact_phone,
                code  : calls.code
            };

            baas_yl.call({
                'http':$http,
                'method': 'post',
                'uri': 'callCenter/index/update',
                'data':data,
                'success': function(d) {
                    if( typeof recall == 'function'){
                        recall( d );
                    }
                }
            });
        }
		,add: function( data,infos,calls,app_id, fn) {

			var params = {
               	serviceType1 : 'yanglao',
               	serviceType1_code:'yanglao',
	            serviceType1_title:'养老服务',
                username:(typeof infos!="undefined"   && typeof infos.name != "undefined"&& infos.name != '' )?infos.name:undefined,
                phone:data.phone==infos.contact_phone?data.phone:infos.contact_phone,
                card_number : data.card_number,
                name:(typeof infos!="undefined"   && typeof infos.name != "undefined" && infos.name != '')?infos.name:undefined,
                code : data.code,
                address:(typeof infos!="undefined"   && typeof infos.address != "undefined" &&infos.address != '' )?infos.address:undefined,
                xingzheng_title :(typeof infos!="undefined"   && typeof infos.xingzheng_title !="undefined"  && infos.xingzheng_title != '' )?infos.xingzheng_title:undefined,
                jiedao_title :(typeof infos!="undefined"   && typeof infos.jiedao_title != "undefined" && infos.jiedao_title != '' )?infos.jiedao_title:undefined,
                shequ_title :(typeof infos!="undefined"   && typeof infos.shequ_title !="undefined"   && infos.shequ_title != '' )?infos.shequ_title:undefined,
                time:data.time,
                detail:data.detail,
                selected_company_code :(data.company_code != ''&& data.company_code != undefined && data.company_code.code !=undefined)? data.company_code.code:'',
                selected_company_phone :(data.company_code != ''&& data.company_code != undefined && data.company_code.code !=undefined)? data.company_code.telephone:'',
//              groupName : data.groupName,
                groupName_title : (data.groupName != ''&& data.groupName != undefined && data.groupName.groupName!=undefined)?data.groupName.groupName:'',
                groupName_code : (data.groupName != ''&& data.groupName != undefined && data.groupName._id!=undefined)?data.groupName._id:'',
                selected_company_name :(data.groupName != ''&& data.groupName != undefined && data.groupName.company_name!=undefined)?data.groupName.company_name[0]:'',
//	            moneys  : data.moneys,
                settlement_name : (data != ''&& data != undefined && data.moneys_name!=undefined)?data.moneys_name:'',
                settlement_price : (data != ''&& data != undefined && data.moneys_price!=undefined)?data.moneys_price:'',
                settlement_code : (data != ''&& data != undefined && data.moneys_code!=undefined)?data.moneys_code:'',
                settlement_unit : (data != ''&& data != undefined && data.moneys_units!=undefined)?data.moneys_units:'',
                //to_app_id:'5096fce5d7f8b112899f5bd7b2302bbe6e08d515'
                to_app_id:friend_app_id
			};

            if( typeof data.serviceType1 != 'undefined' ){
                params.serviceType1 = data.serviceType1.code!=undefined ? data.serviceType1.code : '';
                params.serviceType1_code = data.serviceType1.code!=undefined ? data.serviceType1.code : '';
                params.serviceType1_title = data.serviceType1.title!=undefined ? data.serviceType1.title : '';
            }
            if( typeof data.serviceType2 != 'undefined' ){
                params.serviceType2 = data.serviceType2.code!=undefined ? data.serviceType2.code : '';
                params.serviceType2_code = data.serviceType2.code!=undefined ? data.serviceType2.code : '';
                params.serviceType2_title = data.serviceType2.title!=undefined ? data.serviceType2.title : '';
            }
            if( typeof data.serviceType3 != 'undefined' ){
                params.serviceType3 = data.serviceType3.code!=undefined ? data.serviceType3.code : '';
                params.serviceType3_code = data.serviceType3.code!=undefined ? data.serviceType3.code : '';
                params.serviceType3_title = data.serviceType3.title!=undefined ? data.serviceType3.title : '';
            }
			baas_yl.call({
				'http': $http,
				'method': 'post',
				'uri': 'order/order/addOrder',
				'data': params,
				'success': function(d) {
					if (typeof fn == 'function') {
						fn(d);
					}
				}
			});
		}
        ,edit  : function( data, app_id, recall ){
            var data = {
                phone   : data.phone,
                service     : data.service,
                remark   : data.remark,
                code  : data.code
            };
            baas_yl.call({
                'http':$http,
                'method': 'post',
                'uri': 'callCenter/index/update',
                'data':data,
                'success': function(d) {
                    if( typeof recall == 'function'){
                        recall( d );
                    }
                }
            });
        },
        ring : function( data, app_id, recall ){
            var data = {
                name     : data.name,
                phone     : data.phone
            };

            baas_yl.call({
                'http':$http,
                'method': 'post',
                'uri': 'callCenter/index/ring',
                'data':data,
                'success': function(d) {
                    if(d.status == '1'){
                        if( typeof recall == 'function'){
                            recall( d );
                        }
                    }else{
                        if( d.description ){
                            alert(d.description );
                        }else{
                            alert( '网络原因，请求失败，请稍后重试' );
                        }
                    }
                }
            });
        },
        hangup : function( data,calls, app_id, recall ){
            var data = {
                   code  : calls.code
            };
            baas_yl.call({
                'http':$http,
                'method': 'post',
                'uri': 'callCenter/index/hangup',
                'data':data,
                'success': function(d) {
                    if(d.status == '1'){
                        if( typeof recall == 'function'){
                            recall( d );
                        }
                    }else{
                        if( d.description ){
                            alert(d.description );
                        }else{
                            alert( '网络原因，请求失败，请稍后重试' );
                        }
                    }
                }
            });
        },
        info : function( data, app_id, recall ){
            var data = {
                phone     : data
            };

            baas_yl.call({
                'http':$http,
                'method': 'post',
                'uri': 'callCenter/index/info',
                'data':data,
                'success': function(d) {
                    if( typeof recall == 'function'){
                        recall( d );
                    }
                }
            });
        },
        message : function( data, app_id, recall ){
            var data = {
                name     : data.name,
                phone     : data.phone,
                message   : data.message,
                remark   : data.remark
            };

            baas_yl.call({
                'http': $http,
                'method': 'post',
                'uri': 'callCenter/index/message',
                'data':data,
                'success': function(d) {
                    if( typeof recall == 'function'){
                        recall( d );
                    }
                }
            });
        },
        history : function( data,limit,page,  app_id, recall ){
            var param = {
                limit : limit,
                page : page,
                phone     : (data != ''&& data != undefined)?data.phone:"",
                service     : (data != ''&& data != undefined)?data.service:""
            };

            baas_yl.call({
                'http': $http,
                'method': 'post',
                'uri': 'callCenter/index/history',
                'data':param,
                'success': function(d) {
                    if( typeof recall == 'function'){
                        recall( d );
                    }
                }
            });
        },
        allHistory : function(limit,page, app_id, recall ){
            var param = {
                limit : limit,
                page : page
            };
            baas_yl.call({
                'http': $http,
                'method': 'post',
                'uri': 'callCenter/index/getList',
                'data' : param,
                'success': function(d) {
                    if( typeof recall == 'function'){
                        recall( d );
                    }
                }
            });
        }

        ,find_one : function( code,app_id, fn ){
            baas_yl.call({
                'http': $http,
                'method': 'get',
                'uri': 'callCenter/index/getInfo/'+ code,
                'success': function(d) {
                    if (typeof fn == 'function') {
                        fn(d);
                    }
                }
            });
        }
		//来电历史
		,historys : function( data,limit, page, app_id, recall ){
            var param = {
            	limit : limit,
            	page : page,
                phone:(data != ''&& data != undefined)?data.phone:''
            };
            baas_yl.call({
                'http': $http,
                'method': 'post',
                'uri': 'callCenter/index/history',
                'data':param,
                'success': function(d) {
                     if( typeof recall == 'function'){
	                    recall( d );
	                }
                }
            });
        }
		//服务联动
        ,serviceList :function(code,fn){
			var data = {
	            'code':(code != ''&& code  != undefined)?code:''
	        };
	         baas_yl.call({
		        'http': $http,
		        'method': 'post',
		        'data':data,
		        'uri': 'order/orderList/serviceList',
		        'success': function(d) {
		        	
		        	if (typeof fn == 'function') {
						fn(d);
					}
		        }
		     });
         }
		//老人档案搜索
		,search: function(data, app_id, fn) {
			var data = {
				address : (data.address != undefined) ? data.address : "",
		  		phone: (data.phone != undefined) ? data.phone : "",
		  		name: (data.name != undefined) ? data.name : "",
		  		card_number: (data.card_number != undefined) ? data.card_number : ""
			};
			baas_yl.call({
				'http': $http,
				'method': 'post',
				'uri': 'archives/archives/search',
				'data': data,
				'success': function(d) {
					if (typeof fn == 'function') {
						fn(d);
					}
				}
			});
		}
		//订单历史
		 ,dsearch: function(data,limit, page, app_id, fn) {
			var param = {
				limit: limit,
				page: page,
//             name : (data != ''&& data != undefined)?data.name:'',
               card_number:(data != ''&& data != undefined)?data.card_number:''
			};
			console.log(data.card_number);
			baas_yl.call({
                'http': $http,
                'method': 'post',
                'uri': 'order/orderList/count',
                'data' : param,
                'success': function(d) {
					if( typeof fn == 'function'){
	                    fn( d );
	                }
                }
       		 });
		}
		 //消费记录
		  ,searchCard : function( data,limit, page,app_id, fn ){
            var param = {
            	limit: limit,
				page: page,
				name : (data.name != undefined)?data.name:'',
            	card_id : (data.card_number != undefined)?data.card_number:''
            };
            baas_yl.call({
                'http': $http,
                'method': 'post',
                'uri': 'card/index/searchCard',
                'data' : param,
                'success': function(d) {
                    if( typeof fn == 'function'){
	                    fn( d );
	                }
                }
            });
        }
		   ,yuhistory : function( card_id,limit, page,app_id, fn ){
                var param = {
                    limit: limit,
                    page: page
                };
            baas_yl.call({
                'http': $http,
                'method': 'get',
                'uri': 'card/index/history/'+ card_id,
                'data': param,
                'success': function(d) {
                    if( typeof fn == 'function'){
	                    fn( d );
	                }
                }
            });
        }
	   ,getList: function(limit,page,app_id, fn ){     
            var param = {
                limit : limit,
                page : page
            };
            baas_yl.call({
                'http': $http,
                'method': 'get',
                'uri': 'card/index/list',
                'data':param,
                'success': function(d) {
                    if( typeof fn == 'function'){
	                    fn( d );
	                }
                }
            });
        }
	   //服务商
	   ,getCompany :  function(code,app_id,fn){
	   		var data={
                limit:50
	   		};
	   		baas_jz.call({
	   			'http' : $http,
	   			'method' : 'get',
	   			'data':data,
	   			'uri' : 'company/company/list',
	   			'success' : function(d){
	   				if(typeof fn == 'function'){
	   					fn(d);
	   				}
	   			}
	   		});
	   }
	   //服务站
	   ,getCompanyName : function(groupName,_id,limit,company_code,app_id,fn){
		   	var data = {
		   		'_id':(_id != ''&& _id  != undefined)?_id:'',
		   		limit : limit,
		   		company_code : company_code ,
		   		'groupName' : (groupName != '' && groupName != undefined) ? groupName:''
		   	};
	   		baas_jz.call({
	   			'http' : $http,
	   			'method' : 'get',
	   			'uri' : 'manager/group/list',
	   			'data' : data,
	   			'success' : function(d){
	   				if(typeof fn == 'function'){
	   					fn(d);
	   				}
	   			}
	   		});
	   }
	   //金额
	   ,moneyList : function (data,limit,app_id,fn){
	   		var param = {
	            limit : limit
	        };
            if( typeof data.serviceType3 != 'undefined'){
                param.serviceType3_code = data.serviceType3.code;
            }
            if( typeof data.serviceType2 != 'undefined'){
                param.serviceType2_code = data.serviceType2.code;
            }
	   		baas_jz.call({
	   			'http' : $http,
	   			'method' : 'get',
	   			'uri' : 'order/settlement/list',
	   			'data' : param,
	   			'success' : function(d){
	   				if(typeof fn == 'function'){
	   					fn(d);
	   				}
	   			}
	   		});
	   }
	   //指定服务站
	   ,getCompanyNameList : function(order_id,manager_group_id,app_id,fn){
	   		baas_yl.call({
	   			'http' : $http,
	   			'method' : 'post',
	   			'uri' :'order/orderList/assign/'+order_id+'/manager_group/'+manager_group_id,
                data : {
                  group_app_id :friend_app_id
                },
	   			'success' : function(d){
	   				if(typeof fn == 'function'){
	   					fn(d);
	   				}
	   			}
	   		});
	   }
    };
}

app.factory('callCenterService', ['$http','$location', callCenterService]);
app.controller('callAnswerController', ['$scope','$routeParams','$window','$location','$http','callCenterService',callAnswerController]);
app.controller('callHistoryController', ['$scope','$routeParams','$window','$location','$http','callCenterService',callHistoryController]);
app.controller('callMessageController', ['$scope','$routeParams','$window','$location','$http','callCenterService',callMessageController]);
app.controller('callEditController', ['$scope','$routeParams','$window','$location','$http','callCenterService',callEditController]);
app.controller('elderQueryController', ['$scope', '$routeParams', '$window', '$location', '$http', 'archivesService', elderQueryController]);
app.controller('elderQueryResultController', ['$scope', '$routeParams', '$window', '$location', '$http', 'archivesService', elderQueryResultController]);

function callAnswerController( $scope, $routeParams, $window, $location, $http, callCenterService ){
    $scope.myStyle = true;
    $scope.app_id = $routeParams.app_id;
     
    $scope.info={
    	card_number:""
    }
    //by gxl 20151008
    $scope.btn_status='ok';
    $scope.callStatus = false;
    $scope.init=function(data,$event) {

        if($event.keyCode==8){
        	$scope.btn_status='ok';
            $scope.callStatus = false;
        }else if(data.length<8){
        	console.log(data.length);
        	$scope.btn_status='ok';
            $scope.callStatus = false;
        }
        
    }
    $scope.answer = function( data ){

        var c = /^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$/;
        if(data.phone == '' || !c.test(data.phone)){
            alert("手机号格式不正确！");
            return;
        }
        $scope.callStatus = true;
        //$scope.btn_status ='no';
        callCenterService.answer( data, $scope.app_id,  function( json ){
          $scope.calls = json.data;
        });
        $scope.myStyle = false;
        $scope.searchCardlist(data);
        $scope.selectedPage = 1;
		$scope.limit = 5;
          //来电历史
        $scope.af=true;
        callCenterService.historys(data,$scope.limit,$scope.selectedPage,$scope.app_id,  function( json ){
	        $scope.lists = json.list;
	        $scope.count =  json.count;
            $scope.currentPage =1 ;
            $scope.getPage(json.count);
	    } );
    };
    
    $scope.addCard = function (data){
    	baas_yl.call({
   			'http': $http,
            'method': 'post',
            'uri': 'archives/archives/bind/'+ data.card_number +'/phone/'+data.phone,
            'success': function(d) {
                if(d.status != 1){
                	alert(d.description)
                }else{
                    angular.element('#card').hide();
                    $scope.searchs(data);
                }
            }
   		});
    }
    $scope.searchCardlist = function(data){
	    callCenterService.search(data, $scope.app_id, function(json) {
			if(json!=undefined && json.list.length > 0){
				 $scope.infoList = json.list;
			}else{
                 $scope.infoList = [];
            }
		});
    }
    
    $scope.ring = function( data ){
        var c = /^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$/;
        if(data.phone == '' || !c.test(data.phone)){
            alert("手机号格式不正确！");
            return;
        }
        $scope.callStatus = true;
        //$scope.btn_status='no';
         callCenterService.ring( data, $scope.app_id,  function( json ){
            $scope.calls = json.data;
        } );
        $scope.myStyle = false;
      	$scope.searchCardlist(data);
       
        $scope.selectedPage = 1;
		$scope.limit = 5;
          //来电历史
           $scope.af=true;
        callCenterService.historys(data,$scope.limit,$scope.selectedPage,$scope.app_id,  function( json ){
	        $scope.lists = json.list;
	        $scope.count =  json.count;
            $scope.currentPage =1 ;
            $scope.getPage(json.count);
	    });
    };
   
    $scope.infoList_push = function ( info ){

        if(typeof $scope.infoList == "undefined" || $scope.infoList == "" ){
            $scope.infoList.push( info );
        }else{
            for ( var i = 0; i < $scope.infoList.length ; i ++ ){
                if( $scope.infoList[i].card_number == info.card_number ){
                    return;
                }
            }
        }
    };

    //根据会员卡搜索
    $scope.searchs =function (data){
     	//老人信息
         console.log(data);
         if(typeof data.card_number != "undefined" && data.card_number!="" && data.card_number !== null ){
             $scope.infos_info = {};
             callCenterService.search(data, $scope.app_id, function(json) {
                 $scope.infos_info = json['list'][0];
                 $scope.infoList_push( $scope.infos_info );
                 var address = $scope.infos_info.xingzheng+$scope.infos_info.jiedao+$scope.infos_info.shequ+$scope.infos_info.address;
                 $scope.infos_info.address = address;
                 $scope.infos_info.contact_phone = data.phone;

                 $scope.searchOrder(data);
                 $scope.searchCard(data);

             });
         }else{
             $scope.infos = [];
         }

    }
    $scope.searchCard =function (data){
    	//消费记录
    	$scope.selectedPage = 1;
		$scope.limit = 5;
	    callCenterService.searchCard( data,$scope.limit, $scope.selectedPage,$scope.app_id, function( json ){
            if(json[0].status == -1 ){

                alert("卡片已经注销,请联系管理员");
                $scope.infos = [];
                $scope.info.card_number = null;

                return ;
            } else if(json[0].status == 0 ){

                alert("卡片尚未分配使用者,请联系管理员");
                $scope.infos = [];
                $scope.info.card_number = null;

                return ;
            } else if(json[0].status == 2 ){

                alert("卡片已被停用,请联系管理员");
                $scope.infos = [];
                $scope.info.card_number = null;

                return ;
            } else if(json[0].status != -1 && json[0].status != 0 && json[0].status != 1 && json[0].status != 2) {

                alert("卡片异常,请联系管理员");
                $scope.infos = [];
                $scope.info.card_number = null;

                return ;
            }
            $scope.infos = $scope.infos_info;
            console.log($scope.infos);
            $scope.list = json;
            $scope.thisCardFund = json[0].fund;

            $scope.yuhistory(json);
        });
        $scope.yuhistory = function(lister ){
	        callCenterService.yuhistory( lister[0]["card_id"],$scope.limit, $scope.selectedPage,$scope.app_id, function( json ){
	            $scope.items = json.list;
	        });
	    };
    }
    $scope.searchOrder = function(data){
    	//订单历史
    	if(data.card_number !=undefined && data.card_number != ''){
	    	$scope.selectedPage = 1;
			$scope.limit = 5;
	    	callCenterService.dsearch(data,$scope.limit, $scope.selectedPage,$scope.app_id,function(json){
	        	$scope.list = json['list'];
				$scope.count = json['count'];
				$scope.currentPage = 1;
				$scope.getPage(json['count']);
	        });
	    }else{
    	    alert("会员卡号为空！");
        }
    }

    $scope.showDetailPopup = function(order){
        console.log(order);
        angular.element('#back-order-dialog').modal('show');
        $scope.orderDetail = order;
    }
    
    $scope.hangup = function( data, calls){
        callCenterService.hangup( data,  calls,$scope.app_id,  function( json ){
            alert("已挂断");
            $scope.btn_status='ok';
            $scope.callStatus = false;
            $scope.info={};
            $scope.serviceType1 = '请选择服务项目';
            $scope.serviceType2 = '请选择服务项目';
            $scope.serviceType3 = '请选择服务项目';
            $scope.company_code = '请选择服务商';
            $scope.thisCardFund = '';
            //$scope.groupName = '请选择服务站';
            $scope.money = '请选择服务金额';
            $scope.time ='';
            $scope.infos=[];
            $scope.infoList = [];
            $scope.af=false;
        } );
    };
    //指定服务商
    $scope.getCompanyNameList =function(order_id,manager_group_id){
         callCenterService.getCompanyNameList(order_id,manager_group_id,$scope.app_id,function(json){
             console.log("test===test");
             //$scope.getCompanyNameList = json;
         });
      };
    $scope.update = function( data,infos,calls ){

        if(typeof infos=='undefined')
		{
		    alert("请输入联系方式和地址！");
		    return;
		}
        if(typeof infos.contact_phone=='undefined'|| infos.contact_phone =='')
		{
		   alert("联系方式不能为空！");
		   return;
		}
        $scope.myStyle = true;
        callCenterService.update( data,infos, calls,$scope.app_id,  function( json ){
            $scope.calls.code = json.code;
            alert("保存成功！");
        } );
    };
    $scope.updates = function( data,infos,calls ){
        if(typeof infos=='undefined')
        {
            alert("请输入联系方式和地址！");
            return;
        }
        if(typeof data.money == 'undefined'){
            alert("请选择服务金额");
            return ;
        }
        if(typeof infos.contact_phone=='undefined'|| infos.contact_phone =='')
        {
            alert("联系方式不能为空！");
            return;
        }

        var group_id = (data.groupName != ''&& data.groupName != undefined && data.groupName._id!=undefined)?data.groupName._id:'';
        var code = (data.company_code != ''&& data.company_code != undefined && data.company_code.code !=undefined)? data.company_code.code:'';


        data.phone=angular.element("#phone").val();
    	data.time=angular.element("#time").val();
    	data.detail=angular.element("#exampleTextarea").val();
    	data.moneys = data.money;
		data.moneys_name = data.money.name;
	    data.moneys_price = data.money.price;
	    data.moneys_code = data.money.code;
	    data.moneys_units = data.money.units;

		if(data.time !='' && data.time != undefined ){
              $scope.myStyle = true;
			  callCenterService.add( data,infos,calls, $scope.app_id,  function( json ){

                  if( json.status == 1  ){
                      $scope.info.code = json.code;
                      $scope.order =json['order'];
                      if(typeof data.groupName != 'undefined' && data.groupName !='' ){
//                    	 alert("$scope.order=="+$scope.order);
//                    	 alert("data.groupName._id=="+data.groupName._id);
                          $scope.getCompanyNameList($scope.order,data.groupName._id);
                      }
                      callCenterService.update( data, infos,calls,$scope.app_id,  function( json ){
                          $scope.calls.code = json.code;
                          alert("保存成功！");
                      } );
                  }else{
                      alert( '保存失败' );
                  }
		        } );
		}else{
			alert("请选择预约时间！");
		}
    };

    $scope.getserviceType1 = function(code){
    	callCenterService.serviceList(code,function(d){
    		d.list.shift();
    		d.list.shift();
    		$scope.serviceList1 = d.list;
    	});
   }
    $scope.getserviceType1('0');
    $scope.getserviceType2 = function(code){
        callCenterService.serviceList(code,function(d){
    		$scope.serviceList2 = d.list;
    	});
    }
    $scope.getserviceType2('yanglao');
    $scope.getserviceType3 = function(code){
        callCenterService.serviceList(code,function(d){
    		$scope.serviceList3 = d.list;
            $scope.info.serviceType3 = d.list[0];
            $scope.getMoneyList();
    	});
    }
    //服务金额
    $scope.getMoneyList =function(code){
        $scope.moneyList = [] ;
    	$scope.limit = 500;
        param = {

            serviceType2: $scope.info.serviceType2,
            serviceType3: $scope.info.serviceType3
        };

    	callCenterService.moneyList(param, $scope.limit,$scope.app_id, function(json){

    		angular.forEach(json['list'],function(data,index,list){
                data.text = data.name+data.price+data.units;
            });

            $scope.moneyList = json['list'];
            $scope.info.money = json['list'][0];
    	});

    }
//$scope.getMoneyList();
   // 服务商
    $scope.getCompany =function(code){
    	callCenterService.getCompany(code,$scope.app_id, function( json ){
            $scope.companylist = json['list'];
            
        });
    }
    $scope.getCompany();
   // 服务站
    $scope.getCompanyName =function(company_code){
//	  	var company_code ='12349E';
//		console.log(company_code);
		$scope.limit = 500;
    	if(company_code =='12349E'){
    		callCenterService.getCompanyName($scope.groupName, $scope._id,$scope.limit,company_code,$scope.app_id,function(json){
	    		$scope.companyNameList = json['list'];
                console.log($scope.companyNameList);
	    	});
    	}
    }

    
    $scope.changePage = function( p ){
        $scope.data.selectedPage = p;
        callCenterService.allHistory( $scope.limit,p,$scope.app_id, function( json ){
            $scope.list = json.list;
            $scope.count =  json.count;
            $scope.currentPage = p ;
            $scope.getPage(json.count);
            // console.log( $scope.currentPage)
        });
    };
    $scope.getPage = function(count){
        $scope.pageList = [];
        var limit = 20;//返回的条数
        $scope.totalPage = parseInt(count / limit);//总页数
        $scope.totalPage += count % limit >= 1 ? 1 : 0;//判断页数是否是整数
        var start = ( $scope.currentPage - 2 ) >= 1 ? $scope.currentPage - 2 : 1;//首页
        var end = ( $scope.currentPage + 2 ) <= $scope.totalPage ? $scope.currentPage + 2 : $scope.totalPage;//尾页

        $scope.frontdotShow = start > 1 ? true : false;//前面的省略号
        $scope.backdotShow = end < $scope.totalPage ? true : false;//后面的省略号
        for(var i = start; i <= end; i ++){
            $scope.pageList.push({
                number : i,
                active : i== $scope.currentPage ? 'active':''
            });//给点击的按钮添加class
            // console.log(count);
        }
    };
    
    
    
}

function callHistoryController( $scope, $routeParams, $window, $location, $http, callCenterService ){
    $scope.app_id = $routeParams.app_id;

    $scope.selectedPage = 1;
    $scope.data = {
        selectedPage  : $scope.selectedPage,
        page : $scope.page
    };
    $scope.limit = 20;
    callCenterService.history( $scope.search,$scope.limit,$scope.selectedPage, $scope.app_id,  function( json ){
        $scope.list = json.list;
        $scope.count =  json.count;
        $scope.currentPage = 1 ;
        $scope.getPage(json.count);
       // console.log(json.list)
    } );


    /*分页*/
    $scope.changePage = function( p ){
        $scope.data.selectedPage = p;
        callCenterService.history( $scope.search,$scope.limit,p,$scope.app_id, function( json ){
            $scope.list = json.list;
            $scope.count =  json.count;
            $scope.currentPage = p ;
            $scope.getPage(json.count);
            // console.log( $scope.currentPage)
        });
    };
    $scope.getPage = function(count){
        $scope.pageList = [];
        var limit = 20;//返回的条数
        $scope.totalPage = parseInt(count / limit);//总页数
        $scope.totalPage += count % limit >= 1 ? 1 : 0;//判断页数是否是整数
        var start = ( $scope.currentPage - 2 ) >= 1 ? $scope.currentPage - 2 : 1;//首页
        var end = ( $scope.currentPage + 2 ) <= $scope.totalPage ? $scope.currentPage + 2 : $scope.totalPage;//尾页

        $scope.frontdotShow = start > 1 ? true : false;//前面的省略号
        $scope.backdotShow = end < $scope.totalPage ? true : false;//后面的省略号
        for(var i = start; i <= end; i ++){
            $scope.pageList.push({
                number : i,
                active : i== $scope.currentPage ? 'active':''
            });//给点击的按钮添加class
            // console.log(count);
        }
    };

    $scope.history = function( data ){
        callCenterService.history( data,$scope.limit,$scope.selectedPage, $scope.app_id,  function( json ){
            $scope.list = json.list;
            $scope.count =  json.count;
            $scope.currentPage =1 ;
            $scope.getPage(json.count);
        } );
    };
//  $scope.test=function test () {
//  	angular.element("#test").html()="<div>ww<div>"
//  	
//  }
    //来电历史导出 by gxl 20150917 
    $scope.export = function(data){
        var data = {
                phone   : (data != ''&& data != undefined)?data.phone:"",
                service : (data != ''&& data != undefined)?data.service:""
        };
         baas_yl.call({
	        'http': $http,
	        'method': 'post',
	        'data':data,
	        'uri': 'callCenter/index/export/history',
	        'success': function(d) {
	             if(d.status){
	             	console.log(d.url);
	                $scope.export_url = d.url;
	                console.log("export_url");
	                angular.element('#exportUrl').show();
	            }
	            else
	                alert('网络错误，请重新导出');
	        }
	     });
	     
    };

}

function callMessageController( $scope, $routeParams, $window, $location, $http, callCenterService ){
    $scope.app_id = $routeParams.app_id;

    $scope.message = function( data ){
        callCenterService.message( data, $scope.app_id,  function( json ){
            alert("发送短信");
            $scope.info = [];
        } );
    };
}

function callEditController( $scope, $routeParams, $window, $location, $http, callCenterService ){
    $scope.code = $routeParams.code;
    $scope.app_id = $routeParams.app_id;

    $scope.find_one = function(  ){
        callCenterService.find_one( $scope.code,$scope.app_id,  function( json ){
            $scope.item = json;
             //console.log(json);
        } );
    };
    $scope.find_one();
    $scope.edit = function( data ){

        callCenterService.edit( data, $scope.app_id,  function( json ){
            $scope.info.code = json.code;
            $location.path( '/callCenter/history' );
        } );
        alert("更新成功！");
        $location.path( '/callCenter/history' );
    };
}

function elderQueryController ($scope, $routeParams, $window, $location, $http, archivesService) {

    //  var app_id = '5096fce5d7f8b112899f5bd7b2302bbe6e08d515';
    //  $scope.app_id = '5096fce5d7f8b112899f5bd7b2302bbe6e08d515';
    $scope.app_id = $routeParams.app_id;
    $scope.selectedPage = $routeParams.page;

    $scope.selectedPage = 1;
    $scope.data = {
        selectedPage: $scope.selectedPage,
        page: $scope.page
    };
    $scope.limit = 20;
    $scope.getList = function() {
        archivesService.list($scope.limit, $scope.selectedPage, $scope.app_id, function(json) {
            $scope.list = json['list'];
            $scope.count = json.count;
            $scope.currentPage = 1;
            $scope.getPage(json.count);
        });
    };
    $scope.currentYear = getCurrentYear();
    $scope.getList();
    $scope.search = {};
    $scope.searchArchives = function() {
        //var c = /^\d{8}$/;
        //if( !c.test(search.card_number)){
        //    alert("会员号格式不正确！请输入八位数字");
        //    return;
        //}
        $scope.selectedPage = 1;
        $scope.limit = 20;
        archivesService.search($scope.search, $scope.limit, $scope.selectedPage, $scope.app_id, function(json) {
            $scope.list = json['list'];
            $scope.count = json['count'];
            $scope.currentPage = 1;
            $scope.getPage(json['count']);
        });
    }

    /*分页*/
    $scope.changePage = function(p) {
        $scope.data.selectedPage = p;
        archivesService.search($scope.search,$scope.limit, p, $scope.app_id, function(json) {
            $scope.list = json.list;
            $scope.count = json.count;
            $scope.currentPage = p;
            $scope.getPage(json.count);
        });
    };
    $scope.getPage = function(count) {
        $scope.pageList = [];
        var limit = 20; //返回的条数
        $scope.totalPage = parseInt(count / limit); //总页数
        $scope.totalPage += count % limit >= 1 ? 1 : 0; //判断页数是否是整数
        var start = ($scope.currentPage - 2) >= 1 ? $scope.currentPage - 2 : 1; //首页
        var end = ($scope.currentPage + 2) <= $scope.totalPage ? $scope.currentPage + 2 : $scope.totalPage; //尾页

        $scope.frontdotShow = start > 1 ? true : false; //前面的省略号
        $scope.backdotShow = end < $scope.totalPage ? true : false; //后面的省略号
        for (var i = start; i <= end; i++) {
            $scope.pageList.push({
                number: i,
                active: i == $scope.currentPage ? 'active' : ''
            }); //给点击的按钮添加class
            console.log(count);
        }
    };

    //$scope.delete = function(archives) {
    //    var c = confirm("确定要删除吗？");
    //    if (c == true)
    //    {
    //        archivesService.delete(archives.code, $scope.app_id, function(json) {
    //            if (json.status) {
    //                $scope.getList();
    //            }
    //        });
    //    }
    //
    //}


    //$scope.import = function(  ){
    //    var path = angular.element('#filepath').val();
    //    archivesService.import(path, $scope.app_id, function( json ){
    //        if(json)
    //            alert('导入成功');
    //        else
    //            alert('导入失败，请重新导入');
    //    });
    //}
}

function elderQueryResultController ($scope, $routeParams, $window, $location, $http, archivesService) {

    $scope.code = $routeParams.code;
    $scope.app_id = $routeParams.app_id;
    $scope.pageType = 'edit';
    if ($scope.code == 0) {
        $scope.pageType = 'create';
    }

    if ($scope.pageType == 'edit') {
        archivesService.find_one($scope.code, $scope.app_id, function(json) {

            $scope.archives = json;
            console.log(json);
            $scope.getStreet();
            $scope.getArea();
        });

    }

    /*$scope.getRegion = function(code) {
     //		var code= '20030916001594';
     archivesService.getRegion(code,$scope.app_id, function(json) {
     //console.log(json);
     $scope.region = json;
     });
     }
     $scope.getRegion(0);

     $scope.getStreet = function() {
     //var code = angular.element("#xingzheng").val();
     //		var code = $scope.archives.xingzheng.replace(' ','');
     var code = '20030916001594';
     archivesService.getStreet(code,$scope.app_id,function(json){
     $scope.streets = json;
     });
     };

     $scope.getArea = function() {
     //alert(11);
     //	var code = angular.element("#jiedao").val();
     //   console.log( $scope.archives.jiedao );
     var code = $scope.archives.jiedao.replace(' ','');
     if($scope.archives.jiedao != undefined  ){
     archivesService.getArea(code,$scope.app_id,function(json){
     //console.log(json);
     $scope.areas = json;
     });
     }
     };*/

    $scope.getRegion = function(code) {
        archivesService.getRegion(code,$scope.app_id, function(json) {
            json.shift();json.shift();json.shift();json.shift();json.shift();json.shift();json.shift();json.shift();json.shift();json.shift();json.shift();json.shift();json.shift();json.shift();json.pop();
            $scope.region = json;
        });
    }
    $scope.getRegion(0);
    $scope.getStreet = function(code) {
        var code = '20030916001594';
        archivesService.getRegion(code,$scope.app_id,function(json){
            $scope.streets = json;
        });
    };
    $scope.getArea = function(code) {
//      var code = $scope.archives.jiedao.replace(' ','');
//      if($scope.archives.jiedao != undefined  ){
        archivesService.getRegion(code,$scope.app_id,function(json){
            $scope.areas = json;
        });
//      }
    };

    //$scope.edit = function(data) {
    //    //console.log(data);
    //    data.xingzheng.code = '20030916001594';
    //    data.xingzheng.title = '市北';
    //    archivesService.add(data,$scope.manageId, $scope.app_id, function(json) {
    //        // console.log($scope.manageId)
    //
    //        if (json.status) {
    //            $location.path('/archives');
    //        }
    //    }, $scope.pageType);
    //};
}

function getCurrentYear(){
    var currentDate=new Date();
    return currentDate.getFullYear();
}